#include "Thread.hpp"
#include <vector>

#define NUM 4
using namespace ThreadModule;

// pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int ticknumber = 1000;
class ThreadData{
public:
    pthread_mutex_t* lock_ptr;
    std::string name;
};

void ticket(ThreadData& d){
    while(true){
        pthread_mutex_lock(d.lock_ptr);
        if (ticknumber > 0){
            usleep(1000);
            printf("%s buy a tick, ticknumber is : %d\n",d.name.c_str(), ticknumber--);
            pthread_mutex_unlock(d.lock_ptr);
        }
        else 
        {
            //如果没有票的话，我们需要把锁释放掉。
            pthread_mutex_unlock(d.lock_ptr);
            break; 
        }
        usleep(50);
    }
}   

int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);

    std::vector<Thread<ThreadData>> threads;
    for (int i = 0; i < NUM; i++){
        ThreadData* d = new ThreadData();
        d->lock_ptr = &mutex;
        threads.emplace_back(ticket,*d);
        d->name = threads.back().Name();
    }   

    for (int i = 0; i < NUM; i++){
        threads[i].Start();
    }

    for (int i = 0; i < NUM; i++){
        threads[i].Join();
    }
    return 0;
}